﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using ZhongJia.Core;
using Microsoft.AspNetCore.Http;
using ZhongJia.Core.Extensions;
using System.IO;
using ZhongJia.Core.Caching;
using Microsoft.EntityFrameworkCore;
using GuanQL.Core.Stores;
using GuanQL.Core;
using GuanQL.Core.Domain.Medias;

namespace GuanQL.Service.Medias
{
    public class PictureService : IService
    {
        private readonly IHostingEnvironment _environment;
        private readonly GQLDbContext _dbContext;
        private readonly AppSettings _appSettings;
        private readonly IWebContext _webContext;
        private readonly ICacheClient _cacheClient;

        public PictureService(
             GQLDbContext dbContext,
             IHostingEnvironment environment,
             AppSettings appSettings,
             IWebContext webContext,
             ICacheClient cacheClient)
        {
            _environment = environment;
            _dbContext = dbContext;
            _webContext = webContext;
            _appSettings = appSettings;
            _cacheClient = cacheClient;
        }

        public async Task<Picture> InsertPicture(
           IFormFile file,
           bool isTransient = false,
           bool isSave = false,
           PictureType type = PictureType.Entity)
        {
            if (file == null || file.Length <= 0)
                return null;

            var picture = new Picture
            {
                FileName = file.FileName.Truncate(100),
                IsTransient = isTransient,
                MimeType = file.ContentType,
                Type = type,
                PictureStorage = new PictureStorage
                {
                    Data = await file.OpenReadStream().ToByteArrayAsync(),
                }
            };
            _dbContext.Add(picture);
            if (isSave)
            {
                await _dbContext.SaveChangesAsync();
            }
            return picture;
        }

        public async Task<string> GetPictureUrl(
              Guid pictureId)
        {
            return GetPictureUrl(await _dbContext.Set<Picture>().FindAsync(pictureId));
        }

        public string GetPictureUrl(
                    Picture picture)
        {
            if (picture == null)
                return string.Empty;

            return $"{ _appSettings.ImageHost}/{picture.Id}_{picture.Created.ToString("yyyyMMdd")}_{Path.GetExtension(picture.FileName).Trim('.')}";
        }

        public async Task<IList<Picture>> GetAvatars()
        {
            return await _cacheClient.GetOrCreate("Avatars", async () =>
            {
                return await _dbContext.Set<Picture>().AsNoTracking().Where(p => p.IsSystem && p.Type == PictureType.Avatar).ToListAsync();
            }, TimeSpan.FromDays(1));
        }
    }
}
